package cn.itcast.contacts;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide; // 导入 Glide 库

import java.util.List;

public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.MyViewHolder> {
    private Context mContext;
    private List<ContactInfo> contactInfoList;

    public ContactAdapter(Context context, List<ContactInfo> contactInfoList) {
        this.mContext = context;
        this.contactInfoList = contactInfoList;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        MyViewHolder holder = new MyViewHolder(LayoutInflater.from(mContext).inflate(R.layout.contact_item, parent, false));
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        ContactInfo info = contactInfoList.get(position);
        holder.tv_name.setText(info.getContactName());
        holder.tv_phone.setText(info.getPhoneNumber());

        // 使用 Glide 加载图片，如果图片加载失败，则显示默认图片
        Glide.with(mContext)
                .load(info.getPhotoUri())
                .placeholder(R.drawable.ic_launcher_background) // 加载图片时显示的占位图
                .error(R.drawable.ic_launcher_background) // 加载失败时显示的默认图片
                .into(holder.iv_photo);
    }

    @Override
    public int getItemCount() {
        return contactInfoList.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        TextView tv_name, tv_phone;
        ImageView iv_photo;

        public MyViewHolder(@NonNull View view) {
            super(view);
            tv_name = view.findViewById(R.id.tv_name);
            tv_phone = view.findViewById(R.id.tv_phone);
            iv_photo = view.findViewById(R.id.iv_photo);
        }
    }
}